package com.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.constant.RedisMessageConstant;
import com.entity.Result;
import com.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    /*TODO 注意在controller层中除了这个service使用@Reference注入,redis之类都用@Autowired,*/
   @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;
    @RequestMapping("/check")
    public Result loginCheck(@RequestBody Map map, HttpServletResponse response){
        //校验手机号格式
        String telephone = (String) map.get("telephone");
        /*校验手机号是否正确*/
        if (telephone==null||"".equals(telephone)){
            return new Result(false,"手机号不能为空");
        }
        String s = "^[1][3578]\\d{9}$";
        boolean b = telephone.matches(s);
        if (!b){
            return new Result(false,"手机号输入格式错误");
        }
        //开始提取缓存验证码
        String serviceCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String validateCode = (String) map.get("validateCode");
        if (serviceCode==null||"".equals(serviceCode)||validateCode==null||"".equals(validateCode)){
            //说明是有问题的
            return new Result(false,"提交的手机号与发送验证码的手机号不符合,或者验证码为空");
        }
        //开始真正比对
        if (!serviceCode.equals(validateCode)){
            return new Result(false,"验证码有误");
        }
        //吧手机号传递业务层开始更具体操作
        Result result= null;
        try {
            result = memberService.loginCheck(telephone);
            //把手机号用cookie写回
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
            result= new Result(false,"快速登录失败");
        }

        return result;
    }
}
